<?php

namespace App\Repositories\Api;

use App\Models\Park;
use App\Models\Product;
use App\Models\Supplier;
use App\Repositories\PictureMappingRepository;

/**
 * 店铺
 */
class ShopRepository
{
    public function getList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $res = Supplier::query()
            ->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            })
            ->when(!empty($filter['shopIds']), function ($query) use ($filter) {
                $shopIds = array_unique($filter['shopIds']);
                return $query->whereIn("id", $shopIds);
            })
            ->when(!empty($filter['park_id']), function ($query) use ($filter) {
                return $query->where("park_id", $filter['park_id']);
            })
            ->where(['status' => 1])
            ->orderBy("sort", "asc")
            ->orderBy("id", "desc")
            ->paginate($pageSize, explode(",", "id,store_time,is_open,base_shipping_price,type,title,is_label,bag_price,thumb,deliver_time,min_money,shipping_fee,description,contact_name,ava_price"), null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => & $v) {
            $v['min_money'] = formatNum($v['min_money']);
            $v['shipping_fee'] = formatNum($v['shipping_fee']);
            $v['base_shipping_price'] = json_decode($v['base_shipping_price']);

            !empty($v['store_time']) && $v['store_time'] = json_decode($v['store_time']);

//            is_open  0 ：店铺休息 2：打烊了
            if (!empty($v['store_time']) && $v['is_open'] == 1) {
                if ($v['type'] != 1 && !($v['store_time'][0] <= date("H:i") && $v['store_time'][1] >= date("H:i"))) {
                    $v['is_open'] = 2;
                }
            }
        }

        return $res;
    }

    public function getSearchList($filter = [], $pageNum = 2, $pageSize = 10): array
    {
        $model = Supplier::query();
        if (!empty($filter['shopIds'])) {
            $model->whereIn('id', $filter['shopIds']);
        } else {
            $model->when(!empty($filter['keywords']), function ($query) use ($filter) {
                return $query->where("title", "like", "%{$filter['keywords']}%");
            });
        };
        $res = $model
            /*->when(!empty($filter['park_id']), function ($query) use ($filter) {
                return $query->where("park_id", $filter['park_id']);
            })*/
            ->where("status", 1)
            ->orderBy("id", "desc")
            ->paginate($pageSize, explode(",", "id,type,title,is_label,bag_price,thumb,deliver_time,min_money,description,contact_name,ava_price"), null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);

        foreach ($res['items'] as $k => &$v) {
            $v['products'] = Product::query()
                ->where("shop_id", $v['id'])
                ->where("status", 1)
                ->orderBy("sort", "asc")
                ->orderBy("id", "desc")
                ->limit(4)
                ->get(['id', "title", "thumb", "price", "cost_price"]);
        }

        return $res;
    }

    public function getOne($id = null)
    {
        $res = Supplier::query()->where("id", $id)->first();
        if (empty($res))
            return null;

        $res['min_money'] = formatNum($res['min_money']);
        $res['pictures'] = (new PictureMappingRepository())->getMappingBySearch(['object_type' => 'shop', 'object_id' => $res['id']]);
        $res['base_shipping_price'] = $this->getShippingPrice($res['base_shipping_price']);
        if (!empty($res['store_time']) && intval($res['is_open']) == 1) {
            $res['store_time'] = json_decode($res['store_time'], true);
        }
        if ($res['park_id']) {
            $res['park'] = Park::query()->where(['id' => $res['park_id']])->first(['id', 'title', 'enable_weather_tip']);
        }

        if (!empty($res['store_time']) && $res['is_open'] == 1) {
            if ($res['type'] != 1 && !($res['store_time'][0] <= date("H:i") && $res['store_time'][1] >= date("H:i"))) {
                $res['is_open'] = 2;
            }
        }

        return $res;
    }

    /**
     * 快递费用
     * @param null $base_shipping_price
     * @return void|null
     */
    public function getShippingPrice($base_shipping_price = null)
    {
        if (!$base_shipping_price)
            return null;

        $base_shipping_price = json_decode($base_shipping_price, true);
        foreach ($base_shipping_price as $k => &$v) {
            $v['min'] = intval($v['min']);
            $v['max'] = intval($v['max']);
            $v['total'] = formatNum($v['total']);
        }
        //          SORT_DESC
        array_multisort(array_column($base_shipping_price, 'min'), SORT_ASC, $base_shipping_price);
        return $base_shipping_price;
    }

    public function saveOrUpdate($data = [], $id = 0)
    {
        if (!empty($data['id']))
            unset($data['id']);

        if (intval($id)) {
            Supplier::where("id", $id)->update($data);
            return $id;
        } else {
            $res = Supplier::create($data);
            return $res['id'] ?? "";
        }
    }

    /**
     * 删除
     * @param null $id
     */
    public function deleteShop($id = null)
    {
        if (!intval($id))
            return retFail("参数错误");

        Supplier::where(['id' => intval($id)])->delete();

        return retSuc([], "删除成功");
    }

}
